-
Notifications
You must be signed in to change notification settings - Fork 324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Storages #103
Open
MichalMaM
wants to merge
9
commits into
mbi:master
Choose a base branch
from
MichalMaM:storages
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Storages #103
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
aedb514
added storages package with db and cache storage
MichalMaM a22a408
implemented storage usage to views, fields and managment command
MichalMaM 1c1822a
added CAPTCHA_STORAGE setting to captcha conf with db as default
MichalMaM a20b1ec
fixed tests to work with storages package
MichalMaM c3f9d33
updated docs usage to use storage instead of raw CaptchaStore
MichalMaM 6cb2298
get_storage function can take conf dict as arg now
MichalMaM e247a40
test cache storage too
MichalMaM 00c5703
fixed unicodes for cache save
MichalMaM c9289bd
added CAPTCHA_STORAGE setting to docs
MichalMaM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
from django.core.exceptions import ImproperlyConfigured | ||
from django.utils.module_loading import import_string | ||
|
||
from ..conf import settings as captcha_settings | ||
|
||
|
||
class InvalidStorageBackendError(ImproperlyConfigured): | ||
pass | ||
|
||
|
||
def get_storage(storage_conf=None): | ||
conf = storage_conf or captcha_settings.CAPTCHA_STORAGE | ||
try: | ||
backend = conf['BACKEND'] | ||
# Trying to import the given backend, in case it's a dotted path | ||
backend_cls = import_string(backend) | ||
except (KeyError, ImportError) as e: | ||
raise InvalidStorageBackendError("Could not find storage backend '%s': %s" % ( | ||
backend, e)) | ||
try: | ||
params = conf['PARAMS'].copy() | ||
except KeyError: | ||
params = {} | ||
return backend_cls(params) | ||
|
||
|
||
storage = get_storage() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import datetime | ||
import random | ||
import time | ||
import hashlib | ||
|
||
from django.utils.encoding import smart_text | ||
|
||
from ..models import CaptchaStore | ||
from ..helpers import get_safe_now | ||
from ..conf import settings as captcha_settings | ||
|
||
|
||
# Heavily based on session key generation in Django | ||
# Use the system (hardware-based) random number generator if it exists. | ||
if hasattr(random, 'SystemRandom'): | ||
randrange = random.SystemRandom().randrange | ||
else: | ||
randrange = random.randrange | ||
MAX_RANDOM_KEY = 18446744073709551616 # 2 << 63 | ||
|
||
|
||
class BaseStorage(object): | ||
model_class = CaptchaStore | ||
|
||
def __init__(self, params): | ||
self.params = params | ||
|
||
def create_obj(self, challenge, response, hashkey, expiration): | ||
raise NotImplemented("Override this method in %s" % self.__class__.__name__) | ||
|
||
def delete(self, hashkey, obj=None): | ||
raise NotImplemented("Override this method in %s" % self.__class__.__name__) | ||
|
||
def create(self, challenge, response, hashkey=None, expiration=None): | ||
response = response.lower() | ||
hashkey = hashkey or self.get_hashkey(challenge, response) | ||
expiration = expiration or self.get_expiration() | ||
return self.create_obj(challenge, response, hashkey, expiration) | ||
|
||
def get(self, hashkey): | ||
raise NotImplemented("Override this method in %s" % self.__class__.__name__) | ||
|
||
def delete_wanted(self, hashkey, response, date_to_compare=None): | ||
date_to_compare = date_to_compare or get_safe_now() | ||
obj = self.get(hashkey) | ||
if obj.response != response or obj.expiration <= date_to_compare: | ||
raise self.model_class.DoesNotExist | ||
self.delete(hashkey, obj=obj) | ||
|
||
def get_hashkey(self, challenge, response): | ||
key_ = ( | ||
smart_text(randrange(0, MAX_RANDOM_KEY)) + | ||
smart_text(time.time()) + | ||
smart_text(challenge, errors='ignore') + | ||
smart_text(response, errors='ignore') | ||
).encode('utf8') | ||
return hashlib.sha1(key_).hexdigest() | ||
|
||
def get_expiration(self): | ||
return get_safe_now() + datetime.timedelta(minutes=int(captcha_settings.CAPTCHA_TIMEOUT)) | ||
|
||
def remove_expired(self): | ||
raise NotImplemented("Override this method in %s" % self.__class__.__name__) | ||
|
||
def get_count_of_expired(self): | ||
raise NotImplemented("Override this method in %s" % self.__class__.__name__) | ||
|
||
def generate_key(self): | ||
challenge, response = captcha_settings.get_challenge()() | ||
hashkey = self.get_hashkey(challenge, response) | ||
self.create(challenge=challenge, response=response, hashkey=hashkey) | ||
|
||
return hashkey |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
from django.core.cache import caches | ||
from django.utils.encoding import force_text | ||
|
||
from ..helpers import get_safe_now | ||
from .base import BaseStorage | ||
|
||
|
||
class CacheStorage(BaseStorage): | ||
key_pattern = "captcha_storage_cache_%s" | ||
|
||
def __init__(self, params): | ||
super(CacheStorage, self).__init__(params) | ||
alias = params.get('ALIAS', 'default') | ||
self.cache = caches[alias] | ||
|
||
def get_key(self, hashkey): | ||
return self.key_pattern % hashkey | ||
|
||
def create_obj(self, challenge, response, hashkey, expiration): | ||
key = self.get_key(hashkey) | ||
data = dict( | ||
challenge=force_text(challenge), | ||
response=force_text(response), | ||
hashkey=force_text(hashkey), | ||
expiration=expiration | ||
) | ||
self.cache.set(key, data, timeout=self.get_timeout()) | ||
return self.model_class(**data) | ||
|
||
def delete(self, hashkey, obj=None): | ||
key = self.get_key(hashkey) | ||
self.cache.delete(key) | ||
|
||
def get(self, hashkey): | ||
key = self.get_key(hashkey) | ||
data = self.cache.get(key) | ||
if not data: | ||
raise self.model_class.DoesNotExist | ||
return self.model_class(**data) | ||
|
||
def get_timeout(self): | ||
return (self.get_expiration() - get_safe_now()).total_seconds() | ||
|
||
def remove_expired(self): | ||
""" | ||
In cache keys expired automatically | ||
""" | ||
pass | ||
|
||
def get_count_of_expired(self): | ||
""" | ||
undefined for cache | ||
""" | ||
return None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
from ..helpers import get_safe_now | ||
from .base import BaseStorage | ||
|
||
|
||
class DBStorage(BaseStorage): | ||
|
||
def create_obj(self, challenge, response, hashkey, expiration): | ||
return self.model_class.objects.create( | ||
challenge=challenge, | ||
response=response, | ||
hashkey=hashkey, | ||
expiration=expiration | ||
) | ||
|
||
def delete(self, hashkey, obj=None): | ||
if not obj: | ||
obj = self.get(hashkey) | ||
obj.delete() | ||
|
||
def get(self, hashkey): | ||
return self.model_class.objects.get(hashkey=hashkey) | ||
|
||
def expired_qs(self): | ||
return self.model_class.objects.filter(expiration__lte=get_safe_now()) | ||
|
||
def remove_expired(self): | ||
self.expired_qs().delete() | ||
|
||
def get_count_of_expired(self): | ||
return self.expired_qs().count() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that
model_class
should be set in the DB Storage and not in the base storage. I see that it is used to raiseDoesNotExist
exception but probably will be better if there is a custom exception which will be common for all storages.