Python django.contrib.auth.SESSION_KEY Examples

The following are 26 code examples of django.contrib.auth.SESSION_KEY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth , or try the search function .
Example #1
Source File: protocol.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def getUserFromSessionId(self, session_id):
        """Return the user from `session_id`."""
        session_engine = self.factory.getSessionEngine()
        session_wrapper = session_engine.SessionStore(session_id)
        user_id = session_wrapper.get(SESSION_KEY)
        backend = session_wrapper.get(BACKEND_SESSION_KEY)
        if backend is None:
            return None
        auth_backend = load_backend(backend)
        if user_id is not None and auth_backend is not None:
            user = auth_backend.get_user(user_id)
            # Get the user again prefetching the SSHKey for the user. This is
            # done so a query is not made for each action that is possible on
            # a node in the node listing.
            return (
                User.objects.filter(id=user.id)
                .prefetch_related("sshkey_set")
                .first()
            )
        else:
            return None 
Example #2
Source File: test_sessionstore.py    From django-qsessions with MIT License 6 votes vote down vote up
def test_load_modified(store, django_user_model):
    django_user_model.objects.create_user(username="test_user")

    store[auth.SESSION_KEY] = 1
    store.save()
    store2 = SessionStore(session_key=store.session_key, user_agent="TestUA/1.1-changed", ip="8.8.8.8")
    store2.load()
    assert store2.get(USER_AGENT_SESSION_KEY) == "TestUA/1.1"
    assert store2.get(IP_SESSION_KEY) == "127.0.0.1"
    assert store2.get(auth.SESSION_KEY) == 1
    assert store2.modified is True

    store2.save()

    assert store2.get(USER_AGENT_SESSION_KEY) == "TestUA/1.1-changed"
    assert store2.get(IP_SESSION_KEY) == "8.8.8.8" 
Example #3
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_token_cant_be_used_twice(self):
        key = self.enable_totp()
        r = self.login()
        token = oath.totp(key, timezone.now()),
        r = self.client.post(r['location'], {
            'token': token,
            'type': 'totp',
        })
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id))
        self.client.logout()
        r = self.login()
        r = self.client.post(r['location'], {
            'token': token,
            'type': 'totp',
        })
        self.assertContains(r, TOTPForm.INVALID_ERROR_MESSAGE) 
Example #4
Source File: middleware.py    From django-aws-template with MIT License 6 votes vote down vote up
def get_cached_user(request):
    if not hasattr(request, '_cached_user'):
        try:
            key = CACHE_KEY.format(request.session[SESSION_KEY])
            cache = caches['default']
            user = cache.get(key)
        except KeyError:
            user = AnonymousUser()
        if user is None:
            user = get_user(request)
            cache = caches['default']
            # 8 hours
            cache.set(key, user, 28800)
            logger.debug('No User Cache. Setting now: {0}, {1}'.format(key, user.username))
        request._cached_user = user
    return request._cached_user 
Example #5
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_login_while_already_logged_in(self):
        User.objects.create_superuser(
            username='test2',
            email='test2@example.com',
            password='asdfasdf',
        )
        r = self.client.post(self.login_url, {
            'username': 'test2',
            'password': 'asdfasdf',
            'next': '/next/'
        })
        assert r.status_code == 302

        code = self.enable_backupcode()
        r = self.login()
        self.assertIn(reverse('u2f:verify-second-factor'), r['location'])

        r = self.client.post(r['location'], {
            'code': code,
            'type': 'backup',
        })
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id))
        self.assertTrue(r['location'].endswith('/next/'))
        self.assertFalse(self.user.backup_codes.filter(code=code).exists()) 
Example #6
Source File: functionaltest.py    From dirigible-spreadsheet with MIT License 6 votes vote down vote up
def create_users(self):
        for username in self.get_my_usernames():
            user = User.objects.create(username=username)
            user.set_password('p4ssw0rd')
            user.save()
            profile = user.get_profile()
            profile.has_seen_sheet_page = True
            profile.save()

            # create sessions we can use for login too
            session = SessionStore()
            session[SESSION_KEY] = user.pk
            session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
            session[HASH_SESSION_KEY] = user.get_session_auth_hash()
            session.save()
            self.session_keys[username] = session.session_key 
Example #7
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_login_with_u2f(self):
        code = self.enable_backupcode()
        r = self.client.post(self.login_url, {
            'username': 'test',
            'password': 'asdfasdf',
        })
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertIn(reverse('u2f:verify-second-factor'), r['location'])

        verify_key_response = self.client.get(r['location'])
        self.assertContains(verify_key_response, 'Django administration')

        r = self.client.post(r['location'], {
            'code': code,
            'type': 'backup',
        })

        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id))
        self.assertTrue(r['location'].endswith(self.admin_url)) 
Example #8
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_u2f_login(self):
        self.enable_u2f()
        r = self.login()
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertIn(reverse('u2f:verify-second-factor'), r['location'])

        device_response = self.set_challenge()
        r = self.client.post(r['location'], {
            'response': json.dumps(device_response),
            'type': 'u2f',
        })
        self.assertEquals(r.status_code, 302)
        self.assertTrue(r['location'].endswith('/next/'))
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id)) 
Example #9
Source File: test_account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_logout_returns_204(self):
        password = factory.make_string()
        user = factory.make_User(password=password)
        self.client.handler.enforce_csrf_checks = True
        self.client.login(username=user.username, password=password)
        self.client.handler.enforce_csrf_checks = False
        response = self.client.post(reverse("logout"))
        self.assertThat(response, HasStatusCode(http.client.NO_CONTENT))
        self.assertNotIn(SESSION_KEY, self.client.session) 
Example #10
Source File: activity.py    From django-session-activity with MIT License 5 votes vote down vote up
def get_active_sessions(user, request=None):
    """
    Returns list of all active sessions for given user.

    :type user: django.contrib.auth.models.AbstractBaseUser
    :type request: django.http.HttpRequest
    :return: list of active session info
    :rtype: list of SessionInfo
    """
    SessionStore = get_session_store()
    active_sessions = []

    for obj in SessionActivity.objects.filter(user=user):
        # noinspection PyCallingNonCallable
        session = SessionStore(session_key=obj.session_key)

        if SESSION_KEY in session and session.get_expiry_age():
            session_info = SessionInfo(
                session=session,
                session_key=session.session_key,
                is_current=is_current_session(session, request),
                ip=session.get(SESSION_IP_KEY, None),
                last_used=deserialize_date(session.get(SESSION_LAST_USED_KEY, None)),
                user_agent=session.get(SESSION_USER_AGENT_KEY, ""),
                session_activity=obj
            )
            active_sessions.append(session_info)

    return active_sessions 
Example #11
Source File: utils.py    From django-functest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shortcut_login(self, **credentials):
        user = authenticate(**credentials)
        if not user:
            raise ValueError("User {0} was not authenticated".format(user))

        session_auth_hash = ''
        if hasattr(user, 'get_session_auth_hash'):
            session_auth_hash = user.get_session_auth_hash()

        # Mimicking django.contrib.auth functionality
        self.set_session_data({AUTH_ID_SESSION_KEY: user.pk,
                               AUTH_HASH_SESSION_KEY: session_auth_hash,
                               AUTH_BACKEND_SESSION_KEY: user.backend}) 
Example #12
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_login(self):
        key = self.enable_totp()
        r = self.login()
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertIn(reverse('u2f:verify-second-factor'), r['location'])

        r = self.client.post(r['location'], {
            'token': oath.totp(key, timezone.now()),
            'type': 'totp',
        })
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id))
        self.assertTrue(r['location'].endswith('/next/')) 
Example #13
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_incorrect_code(self):
        self.enable_backupcode()
        r = self.login()
        r = self.client.post(r['location'], {
            'code': 'abc',
            'type': 'backup',
        })
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertContains(r, BackupCodeForm.INVALID_ERROR_MESSAGE) 
Example #14
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_code_required_and_login(self):
        code = self.enable_backupcode()
        r = self.login()
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertIn(reverse('u2f:verify-second-factor'), r['location'])

        r = self.client.post(r['location'], {
            'code': code,
            'type': 'backup',
        })
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id))
        self.assertTrue(r['location'].endswith('/next/'))
        self.assertFalse(self.user.backup_codes.filter(code=code).exists()) 
Example #15
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_login_without_u2f(self):
        r = self.client.post(self.login_url, {
            'username': 'test',
            'password': 'asdfasdf',
            'this_is_the_login_form': 1,
            'next': self.admin_url,
        })
        self.assertTrue(r['location'].endswith(self.admin_url))
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id)) 
Example #16
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_failed_u2f_login(self):
        self.enable_u2f()
        r = self.login()
        device_response = self.set_challenge()
        device_response['signatureData'] = 'a' + device_response['signatureData'][1:]
        r = self.client.post(r['location'], {
            'response': json.dumps(device_response),
            'type': 'u2f',
        })
        self.assertNotIn(SESSION_KEY, self.client.session)
        self.assertContains(r, 'U2F validation failed') 
Example #17
Source File: test_sessionstore.py    From django-qsessions with MIT License 5 votes vote down vote up
def test_auth_session_key(store):
    assert auth.SESSION_KEY not in store
    assert store.modified is False
    assert store.accessed is True

    store.get(auth.SESSION_KEY)
    assert store.modified is False

    store[auth.SESSION_KEY] = 1
    assert store.modified is True 
Example #18
Source File: tests.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_normal_login(self):
        r = self.login()
        self.assertTrue(r['location'].endswith('/next/'))
        self.assertEqual(str(self.client.session[SESSION_KEY]), str(self.user.id)) 
Example #19
Source File: api.py    From django-user-messages with MIT License 5 votes vote down vote up
def get_messages(request=None, user=None):
    assert bool(request) != bool(user), "Pass exactly one of request or user"
    _nonlocal = (user,)

    def fetch():
        messages = []
        (user,) = _nonlocal

        if request is not None:
            messages.extend(api.get_messages(request))
            if request.session.get(SESSION_KEY) and request.user.is_authenticated:
                user = request.user

        if user is not None:
            from user_messages.models import Message

            user_messages = Message.objects.filter(
                user=user, delivered_at__isnull=True
            ).order_by("pk")
            messages.extend(user_messages)
            if any(m.deliver_once for m in user_messages):
                user_messages.filter(deliver_once=True).update(
                    delivered_at=timezone.now()
                )

        return messages

    return SimpleLazyObject(fetch) 
Example #20
Source File: db.py    From acacia_main with MIT License 5 votes vote down vote up
def __setitem__(self, key, value):
        if key == auth.SESSION_KEY:
            self.user_id = value
        super(SessionStore, self).__setitem__(key, value) 
Example #21
Source File: sessions.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_session_dict_user(session_dict: Mapping[str, int]) -> Optional[int]:
    # Compare django.contrib.auth._get_user_session_key
    try:
        return get_user_model()._meta.pk.to_python(session_dict[SESSION_KEY])
    except KeyError:
        return None 
Example #22
Source File: db.py    From django-qsessions with MIT License 5 votes vote down vote up
def create_model_instance(self, data):
        # Store User, User Agent, and IP in Session (in DB).
        return self.model(
            session_key=self._get_or_create_session_key(),
            session_data=self.encode(data),
            expire_date=self.get_expiry_date(),
            user_id=self.get(auth.SESSION_KEY),
            user_agent=self.user_agent,
            ip=self.ip,
        ) 
Example #23
Source File: test_model.py    From django-qsessions with MIT License 5 votes vote down vote up
def test_get_decoded(django_user_model):
    django_user_model.objects.create_user(username="test_user")

    store = SessionStore(user_agent="TestUA/1.1", ip="127.0.0.1")
    store[auth.SESSION_KEY] = 1
    store["foo"] = "bar"
    store.save()

    session = Session.objects.get(pk=store.session_key)
    assert session.get_decoded() == {
        "foo": "bar",
        auth.SESSION_KEY: 1,
        IP_SESSION_KEY: "127.0.0.1",
        USER_AGENT_SESSION_KEY: "TestUA/1.1",
    } 
Example #24
Source File: test_sessionstore.py    From django-qsessions with MIT License 5 votes vote down vote up
def test_clear(store):
    """
    Clearing the session should clear all non-browser information
    """
    store[auth.SESSION_KEY] = 1
    store.clear()
    store.save()

    session = Session.objects.get(pk=store.session_key)
    assert session.user_id is None 
Example #25
Source File: test_sessionstore.py    From django-qsessions with MIT License 5 votes vote down vote up
def test_load_unmodified(store, django_user_model):
    django_user_model.objects.create_user(username="test_user")

    store[auth.SESSION_KEY] = 1
    store.save()
    store2 = SessionStore(session_key=store.session_key, user_agent="TestUA/1.1", ip="127.0.0.1")
    store2.load()
    assert store2.get(USER_AGENT_SESSION_KEY) == "TestUA/1.1"
    assert store2.get(IP_SESSION_KEY) == "127.0.0.1"
    assert store2.get(auth.SESSION_KEY) == 1
    assert store2.modified is False 
Example #26
Source File: test_sessionstore.py    From django-qsessions with MIT License 5 votes vote down vote up
def test_save(store, django_user_model):
    django_user_model.objects.create_user(username="test_user")

    store[auth.SESSION_KEY] = 1
    store.save()

    session = Session.objects.get(pk=store.session_key)
    assert session.user_agent == "TestUA/1.1"
    assert session.ip == "127.0.0.1"
    assert session.user_id == 1
    assert now() - timedelta(seconds=5) <= session.updated_at <= now()