Пример #1
0
def patched_redis(settings):
    patch_redis(REDIS_DB_FILE)
    _redis = StrictRedis(REDIS_DB_FILE)
    settings.REDIS_URL = 'unix://{}'.format(_redis.socket_file)
    _redis.flushall()
    yield _redis
    unpatch_redis()
Пример #2
0
    def setUp(self):
        # We create a superuser and a client with all scopes
        # Then we create token with smaller scopes to test
        person_content_type = ContentType.objects.get_for_model(Person)
        self.person = Person.objects.create_superperson(
            email='*****@*****.**', password='******')
        add_permission = Permission.objects.get(
            content_type=person_content_type, codename='view_person')
        self.person.role.user_permissions.add(add_permission)
        self.other_person = Person.objects.create(email='*****@*****.**')

        self.calendar = Calendar.objects.create_calendar('calendar')
        self.event = Event.objects.create(name='Test event',
                                          start_time=timezone.now(),
                                          end_time=timezone.now() +
                                          timezone.timedelta(hours=4),
                                          calendar=self.calendar)

        OrganizerConfig.objects.create(event=self.event, person=self.person)

        self.api_client = models.Client.objects.create_client(
            'client', scopes=scopes.scopes_names)
        self.redis_instance = StrictRedis()
        self.redis_patcher = mock.patch('clients.tokens.get_auth_redis_client')
        mock_get_auth_redis_client = self.redis_patcher.start()
        mock_get_auth_redis_client.return_value = self.redis_instance
Пример #3
0
    def test_not_eager(self, registry: CollectorRegistry, redis: StrictRedis):
        counter = Counter(name="http_requests_total",
                          description="Total HTTP Requests")
        registry.register(counter)

        assert not registry.eager

        counter.inc()

        assert redis.hgetall("testing") == {}

        registry.transfer()

        assert redis.hgetall("testing") != {}
Пример #4
0
def test_redis_getter_setter(tmpdir):
    """:type tmpdir: py.path.local"""

    from cache_requests import Memoize
    from redislite import StrictRedis

    # LOCAL SETUP
    # ------------------------------------------------------------------------
    @Memoize(ex=1)
    def hello():
        pass

    test_connection = hello.redis
    test_db = tmpdir.join('test_redis.db').strpath
    alt_db = tmpdir.join('test_redis_getter_setter.db').strpath
    alt_connection = StrictRedis(dbfilename=alt_db)

    # TEST SETUP
    # ------------------------------------------------------------------------
    assert test_connection.db == test_db
    assert alt_connection.db == alt_db
    assert test_db != alt_db

    # TEST MEMOIZE REDIS SETTER
    # ------------------------------------------------------------------------
    hello.redis = alt_connection

    assert hello.redis.db != test_db
    assert hello.redis.db == alt_db
Пример #5
0
    def setUp(self):
        self.person = Person.objects.create_person(email='*****@*****.**')
        self.scope = scopes.view_profile
        self.other_scope = scopes.edit_profile
        self.client = models.Client.objects.create_client(
            'client', scopes=[self.scope.name, self.other_scope.name])
        self.one_scope_client = models.Client.objects.create_client(
            'noscope', scopes=[self.other_scope.name])

        self.redis_instance = StrictRedis()

        self.token = str(uuid.uuid4())
        self.token_info = {
            'clientId': self.client.label,
            'userId': str(self.person.pk),
            'scope': [self.scope.name, self.other_scope.name]
        }

        self.wrong_scope_token = str(uuid.uuid4())
        self.wrong_scope_token_info = {
            'clientId': self.one_scope_client.label,
            'userId': str(self.person.pk),
            'scope': [self.scope.name, self.other_scope.name]
        }

        self.redis_instance.set(
            '{prefix}{token}:payload'.format(prefix=settings.AUTH_REDIS_PREFIX,
                                             token=self.token),
            json.dumps(self.token_info))

        self.redis_instance.set(
            '{prefix}{token}:payload'.format(prefix=settings.AUTH_REDIS_PREFIX,
                                             token=self.wrong_scope_token),
            json.dumps(self.wrong_scope_token_info))

        self.redis_patcher = mock.patch('clients.tokens.get_auth_redis_client')
        mock_get_auth_redis_client = self.redis_patcher.start()
        mock_get_auth_redis_client.return_value = self.redis_instance

        self.factory = APIRequestFactory()
        self.token_authentifier = authentication.AccessTokenAuthentication()
Пример #6
0
def test_redis_getter_setter(tmpdir):
    """:type tmpdir: py.path.local"""

    from cache_requests import Session
    from redislite import StrictRedis

    # LOCAL SETUP
    # ------------------------------------------------------------------------
    request = Session()

    test_db = tmpdir.join('test_redis.db').strpath
    test_connection = request.cache.connection
    alt_db = tmpdir.join('test_redis_getter_setter.db').strpath
    alt_connection = StrictRedis(dbfilename=alt_db)

    # TEST SETUP
    # ------------------------------------------------------------------------
    assert test_connection.db == test_db
    assert alt_connection.db == alt_db
    assert test_db != alt_db

    # TEST SESSION CONNECTION IDENTITY WITH METHOD's REDIS HANDLE
    # ------------------------------------------------------------------------

    assert request.get.redis is request.cache.connection
    assert request.cache.connection.db == test_db

    request.post.redis = alt_connection

    assert request.post.redis is request.patch.redis
    assert request.post.redis is request.cache.connection
    assert request.post.redis.db == alt_db

    request.cache.connection = test_connection

    assert request.delete.redis is request.patch.redis
    assert request.delete.redis is request.cache.connection
    assert request.delete.redis.db == test_db
Пример #7
0
import json

from redislite import StrictRedis
from tornado.testing import AsyncHTTPTestCase
from tornado.web import create_signed_value

from core.db.models import User
from core.session.model import Session
from core.webserver import WebServer
from core.utils.config import parse_config

app = None
config = parse_config('config/test.conf')
redis_server = StrictRedis(decode_responses=True)
config.set('redis', 'socket', redis_server.socket_file)


def end_transactions(session):
    session.rollback() if session else None


def get_global_app():
    global app
    app = WebServer(config=config) if app is None else app
    return app


class BaseAppTestCase(AsyncHTTPTestCase):
    def setUp(self):
        super().setUp()
        self.addCleanup(end_transactions, session=self.db)
Пример #8
0
class TokenTestCase(TestCase):
    def setUp(self):
        self.person = Person.objects.create_person(email='*****@*****.**')
        self.scope = scopes.view_profile
        self.other_scope = scopes.edit_profile
        self.client = models.Client.objects.create_client(
            'client', scopes=[self.scope.name, self.other_scope.name])
        self.one_scope_client = models.Client.objects.create_client(
            'noscope', scopes=[self.other_scope.name])

        self.redis_instance = StrictRedis()

        self.token = str(uuid.uuid4())
        self.token_info = {
            'clientId': self.client.label,
            'userId': str(self.person.pk),
            'scope': [self.scope.name, self.other_scope.name]
        }

        self.wrong_scope_token = str(uuid.uuid4())
        self.wrong_scope_token_info = {
            'clientId': self.one_scope_client.label,
            'userId': str(self.person.pk),
            'scope': [self.scope.name, self.other_scope.name]
        }

        self.redis_instance.set(
            '{prefix}{token}:payload'.format(prefix=settings.AUTH_REDIS_PREFIX,
                                             token=self.token),
            json.dumps(self.token_info))

        self.redis_instance.set(
            '{prefix}{token}:payload'.format(prefix=settings.AUTH_REDIS_PREFIX,
                                             token=self.wrong_scope_token),
            json.dumps(self.wrong_scope_token_info))

        self.redis_patcher = mock.patch('clients.tokens.get_auth_redis_client')
        mock_get_auth_redis_client = self.redis_patcher.start()
        mock_get_auth_redis_client.return_value = self.redis_instance

        self.factory = APIRequestFactory()
        self.token_authentifier = authentication.AccessTokenAuthentication()

    def tearDown(self):
        self.redis_patcher.stop()

    def test_cannot_authenticate_with_invalid_token(self):
        request = self.factory.get('',
                                   HTTP_AUTHORIZATION="Bearer {token}".format(
                                       token=str(uuid.uuid4())))

        with self.assertRaises(exceptions.AuthenticationFailed):
            self.token_authentifier.authenticate(request=request)

    def test_can_authenticate_with_token(self):
        request = self.factory.get(
            '', HTTP_AUTHORIZATION="Bearer {token}".format(token=self.token))

        auth_user, auth_info = self.token_authentifier.authenticate(
            request=request)

        self.assertEqual(auth_user.type, Role.PERSON_ROLE)
        self.assertEqual(auth_user.person, self.person)
        self.assertEqual(auth_user.token, auth_info)
        self.assertIsInstance(auth_info, tokens.AccessToken)
        self.assertEqual(auth_info.client, self.client)
        self.assertCountEqual(auth_info.scopes, [self.scope, self.other_scope])

    def test_only_scopes_authorized_for_client_are_kept(self):
        request = self.factory.get('',
                                   HTTP_AUTHORIZATION="Bearer {token}".format(
                                       token=self.wrong_scope_token))

        auth_user, auth_info = self.token_authentifier.authenticate(
            request=request)

        self.assertEqual(auth_info.client, self.one_scope_client)
        self.assertCountEqual(auth_info.scopes, [self.other_scope])
Пример #9
0
class ScopeTestCase(APITestCase):
    def setUp(self):
        # We create a superuser and a client with all scopes
        # Then we create token with smaller scopes to test
        person_content_type = ContentType.objects.get_for_model(Person)
        self.person = Person.objects.create_superperson(
            email='*****@*****.**', password='******')
        add_permission = Permission.objects.get(
            content_type=person_content_type, codename='view_person')
        self.person.role.user_permissions.add(add_permission)
        self.other_person = Person.objects.create(email='*****@*****.**')

        self.calendar = Calendar.objects.create_calendar('calendar')
        self.event = Event.objects.create(name='Test event',
                                          start_time=timezone.now(),
                                          end_time=timezone.now() +
                                          timezone.timedelta(hours=4),
                                          calendar=self.calendar)

        OrganizerConfig.objects.create(event=self.event, person=self.person)

        self.api_client = models.Client.objects.create_client(
            'client', scopes=scopes.scopes_names)
        self.redis_instance = StrictRedis()
        self.redis_patcher = mock.patch('clients.tokens.get_auth_redis_client')
        mock_get_auth_redis_client = self.redis_patcher.start()
        mock_get_auth_redis_client.return_value = self.redis_instance

    def tearDown(self):
        self.redis_patcher.stop()

    def generate_token(self, scopes_names):
        self.token = str(uuid.uuid4())
        self.token_info = {
            'clientId': self.api_client.label,
            'userId': str(self.person.pk),
            'scope': scopes_names
        }
        self.redis_instance.set(
            '{prefix}{token}:payload'.format(prefix=settings.AUTH_REDIS_PREFIX,
                                             token=self.token),
            json.dumps(self.token_info))
        self.client.credentials(HTTP_AUTHORIZATION="Bearer {token}".format(
            token=self.token))

    def test_get_required_token(self):
        self.assertEqual(scopes.get_required_scopes('people.view_person'),
                         [scopes.view_profile])

    def test_can_view_profile_with_correct_scope(self):
        self.generate_token([scopes.view_profile.name])
        response = self.client.get('/legacy/people/me/')
        self.assertEqual(response.status_code, 200)

    def test_cannot_view_profile_without_correct_scope(self):
        self.generate_token([scopes.edit_event.name])
        response = self.client.get('/legacy/people/me/')
        self.assertEqual(response.status_code, 403)

    def test_cannot_use_global_permissions_with_token(self):
        self.generate_token([scopes.view_profile.name])
        response = self.client.get('/legacy/people/' +
                                   str(self.other_person.id) + '/')
        self.assertEqual(response.status_code, 403)

    def test_can_edit_profile_with_correct_scope(self):
        self.generate_token([scopes.edit_profile.name])
        response = self.client.patch('/legacy/people/' + str(self.person.id) +
                                     '/',
                                     data={'email': '*****@*****.**'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.person.email, '*****@*****.**')

    def test_cannot_edit_profile_without_correct_scope(self):
        self.generate_token([scopes.view_profile.name])
        response = self.client.patch('/legacy/people/' + str(self.person.id) +
                                     '/',
                                     data={'email': '*****@*****.**'})
        self.assertEqual(response.status_code, 403)

    def test_can_edit_own_event_with_correct_scope(self):
        self.generate_token([scopes.edit_event.name])
        response = self.client.patch('/legacy/events/' + str(self.event.id) +
                                     '/',
                                     data={'description': 'Description !'})
        self.event.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.event.description, 'Description !')

    def test_cannot_edit_own_event_without_correct_scope(self):
        self.generate_token([scopes.view_profile.name])
        response = self.client.patch('/legacy/events/' + str(self.event.id) +
                                     '/',
                                     data={'description': 'Description !'})
        self.event.refresh_from_db()
        self.assertEqual(response.status_code, 403)
Пример #10
0
#pip intall redislite

from redislite import StrictRedis
from redis_collections import List


def read_temp_celsius():
    with open('file/to/driver/w1_slave') as device:
        for line in device:
            value = line.strip().split()[-1]
            if value.startswith('t='):
                return float(value[2:]) / 1000.0


redis_connection = StrictRedis('')

#using wemos-d1-mini ESP8266 (wifi built in) with micropython...

import dht
import machine

print "Powering on sensor"
power_pin = machine.Pin()
power_pin.high()

print "Reading sensor"
d = dht.DHT11(machine.Pin(0))
d.measure()
print "Temp", d.temperature() * 1.8 + 32
print "Humidity", d.humidity()
Пример #11
0
def redis():
    return StrictRedis(db=0)
Пример #12
0
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400

LOGIN_REDIRECT_URL = "home_question"

ACCOUNT_LOGOUT_REDIRECT_URL = 'home'

# Email Settings
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

EMAIL_HOST = 'localhost'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

redis = StrictRedis("/dev/shm/cache.rdb")

CACHES = {
    'default': {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "unix://@%s" % (redis.socket_file, )
    },
    'select2': {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "unix://@%s" % (redis.socket_file, )
    }
}

CRISPY_TEMPLATE_PACK = 'bootstrap4'

# Tell select2 which cache configuration to use:
Пример #13
0
import schedule
from time import sleep
from flask_bootstrap import Bootstrap
from collections import OrderedDict
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField
from wtforms.validators import Length, ValidationError
from flask import Flask, render_template, request, url_for, Response, abort
from datetime import datetime
from redislite import StrictRedis

app = Flask(__name__, static_url_path="/static")
Bootstrap(app)
app.config["SECRET_KEY"] = settings.csrf
REDIS = os.path.join("/tmp/redis.db")
r = StrictRedis(REDIS, charset="utf-8", decode_responses=True)
r.hset("counter", "increment", 0)


def reset_redis():
    r.hset("counter", "increment", 0)


schedule.every().hour.do(reset_redis)


class WebForm(FlaskForm):
    """ for validation """

    webabstract = TextAreaField(validators=[
        Length(
Пример #14
0
def redis(tmpdir):
    yield StrictRedis(str(tmpdir.join('redis.db')))
                                                    backupCount=5,
                                                    encoding='utf-8')
file_handler.setLevel(logging.INFO)

app = Flask(__name__)
app.logger.addHandler(file_handler)

try:
    # noinspection PyUnresolvedReferences
    from redislite import StrictRedis
    # noinspection PyUnresolvedReferences
    from werkzeug.contrib.cache import RedisCache

    cache_file = os.path.join(os.path.dirname(__file__), 'server_cache.rdb')

    cache = RedisCache(StrictRedis(cache_file))
except ImportError:
    from werkzeug.contrib.cache import SimpleCache

    cache = SimpleCache()
    app.logger.warning(
        'redislite could not be imported. Falling back to non-thread-safe caching'
    )

try:
    with open('message.json') as f:
        secret_message = json.load(f)
except IOError:
    raise RuntimeError('Use %r to create the database first. %r not found. \n'
                       'Shutting down...' % ('make migrate', 'message.json'))