Example #1
0
def getItem(context, request):

    response = Response(content_type='application/json')

    json_files = [
        '/q1/item.json', '/q2/item.json', '/q3/item.json', '/q4/item.json',
        '/q5/item.json'
    ]

    try:
        # get cookies
        cookieval = request.cookies['signed_cookie']
        cookies = signed_deserialize(cookieval, 'secret')
        count = cookies['c']

        # set next one
        next_count = count + 1
        cookieval = signed_serialize({'c': next_count}, 'secret')
        response.set_cookie('signed_cookie', cookieval)

    except KeyError:
        cookieval = signed_serialize({'c': 0}, 'secret')
        response.set_cookie('signed_cookie', cookieval)
        count = 0

    json_file = item_path + json_files[count]

    with open(json_file, 'r') as myfile:
        json_data = myfile.read()

    response.charset = 'utf8'
    response.text = json_data
    return response
def _set_cookie(
    session,
    request,
    response,
    cookie_name,
    cookie_max_age,
    cookie_path,
    cookie_domain,
    cookie_secure,
    cookie_httponly,
    secret,
):
    """
    `session` is via functools.partial
    `request` and `response` are appended by add_response_callback
    """
    cookieval = signed_serialize(session.session_id, secret)
    response.set_cookie(
        cookie_name,
        value=cookieval,
        max_age=cookie_max_age,
        path=cookie_path,
        domain=cookie_domain,
        secure=cookie_secure,
        httponly=cookie_httponly,
    )
Example #3
0
def _set_cookie(
    session,
    request,
    response,
    cookie_name,
    cookie_max_age,
    cookie_path,
    cookie_domain,
    cookie_secure,
    cookie_httponly,
    secret,
):
    """
    `session` is via functools.partial
    `request` and `response` are appended by add_response_callback
    """
    cookieval = signed_serialize(session.session_id, secret)
    response.set_cookie(
        cookie_name,
        value=cookieval,
        max_age=cookie_max_age,
        path=cookie_path,
        domain=cookie_domain,
        secure=cookie_secure,
        httponly=cookie_httponly,
    )
Example #4
0
 def set_cookie_callback(request, response):
     cookieval = signed_serialize(session_key, secret)
     response.set_cookie(
         cookie_name,
         value = cookieval,
         max_age = cookie_max_age,
         domain = cookie_domain,
         secure = cookie_secure,
         httponly = cookie_httponly,
         )
 def create_session(self, response, username):
     cookie_val = signed_serialize({'session': uuid.uuid4().hex},
                                   os.getenv('WICS_SECRET', '1h3$L6'))
     response.set_cookie('session', cookie_val)
     self.sessions[cookie_val] = {
         'expires':
         datetime.datetime.now() + datetime.timedelta(minutes=15),
         'user': username,
     }
     return response
Example #6
0
 def test_cookie_already_set_new_session(self):
     factory = self._makeOne('secret')
     request = testing.DummyRequest()
     request.cookies['session_id'] = signed_serialize('1', 'secret')
     connection = DummyConnection()
     def get_connection(request, dbname):
         self.assertEqual(dbname, None)
         return connection
     session = factory(request, get_connection=get_connection)
     self.assertEqual(len(request.response_callbacks), 0)
     self.assertEqual(session.id, '1')
     self.assertTrue(session._v_new)
    def _set_cookie(self, response, cookie_name, cookie_val):

        cookieval = signed_serialize(cookie_val, self.secret)

        response.set_cookie(
            cookie_name,
            value=cookieval,
            max_age=self.set_cookie_attributes.get('cookie_max_age', None),
            path=self.set_cookie_attributes.get('cookie_path', None),
            domain=self.set_cookie_attributes.get('cookie_domain', None),
            secure=self.set_cookie_attributes.get('cookie_secure', None),
            httponly=self.set_cookie_attributes.get('cookie_httponly', None))
    def _set_cookie(self, response, cookie_name, cookie_val):

        cookieval = signed_serialize(cookie_val, self.secret)

        response.set_cookie(
            cookie_name,
            value=cookieval,
            max_age=self.set_cookie_attributes.get('cookie_max_age', None),
            path=self.set_cookie_attributes.get('cookie_path', None),
            domain=self.set_cookie_attributes.get('cookie_domain', None),
            secure=self.set_cookie_attributes.get('cookie_secure', None),
            httponly=self.set_cookie_attributes.get('cookie_httponly', None))
Example #9
0
def set_session_id(response, cookie_name, secret, session_id, **kwargs):
    """
    Sets the session id on the response.
    :param response:
    :param cookie_name:
    :param secret:
    :param session_id:
    :return:
    """
    response.set_cookie(cookie_name, signed_serialize(session_id, secret),
                        **kwargs)
    return response
Example #10
0
 def test_cookie_already_set_existing_session(self):
     from . import PyramidSessionDataManager
     factory = self._makeOne('secret')
     request = testing.DummyRequest()
     request.cookies['session_id'] = signed_serialize('1', 'secret')
     manager = PyramidSessionDataManager(10, 5)
     expected = manager.get('1')
     root = {'sessions':manager}
     connection = DummyConnection(root)
     def get_connection(request, dbname):
         self.assertEqual(dbname, None)
         return connection
     session = factory(request, get_connection=get_connection)
     self.assertEqual(session, expected)
Example #11
0
 def login(self, request):
     if request.method == 'POST':
         login = request.POST.get('login')
         password = request.POST.get('password')
         if login and password:
             user = dbs.query(StaffModel).filter_by(name=login).first()
             if user and user.password == sha256(
                     password + user.salt).hexdigest():
                 now = datetime.datetime.utcnow()
                 csrf = sha256(str(now)).hexdigest()
                 val = signed_serialize({'time': now, 'csrf': csrf}, SECRET)
                 response = HTTPFound(request.route_url('admin.index'))
                 response.set_cookie('signed', val)
                 return response
             return dict(
                 error='Something went wrong. Try "admin" and "111111"')
     return {}
Example #12
0
        def _set_cookie(self, response):
            if not self._cookie_on_exception:
                exception = getattr(self.request, 'exception', None)
                if exception is not None:  # don't set cookie during exceptions
                    return False

            self.save()
            cookieval = signed_serialize(
                (self.accessed, self.created, self['_id']), self._secret
                )
            response.set_cookie(
                self._cookie_name,
                value=cookieval,
                max_age=self._cookie_max_age,
                path=self._cookie_path,
                domain=self._cookie_domain,
                secure=self._cookie_secure,
                httponly=self._cookie_httponly,
                )
            return True
            def set_cookie_callback(request, response):
                """
                The set cookie callback will first check to see if we're in an
                exception. If we're in an exception and ``cookie_on_exception``
                is False, we return immediately before setting the cookie.

                For all other cases the cookie will be set normally.
                """
                exc = getattr(request, 'exception', None)
                if exc is not None and cookie_on_exception is False:
                    return
                cookieval = signed_serialize(session_key, secret)
                response.set_cookie(
                    cookie_name,
                    value=cookieval,
                    max_age=cookie_max_age,
                    domain=cookie_domain,
                    secure=cookie_secure,
                    httponly=cookie_httponly,
                    )
Example #14
0
def _set_cookie(
    request,
    response,
    cookie_name,
    cookie_max_age,
    cookie_path,
    cookie_domain,
    cookie_secure,
    cookie_httponly,
    secret,
):
    cookieval = signed_serialize(request.session.session_id, secret)
    response.set_cookie(
        cookie_name,
        value=cookieval,
        max_age=cookie_max_age,
        path=cookie_path,
        domain=cookie_domain,
        secure=cookie_secure,
        httponly=cookie_httponly,
    )
def _set_cookie(
    request,
    response,
    cookie_name,
    cookie_max_age,
    cookie_path,
    cookie_domain,
    cookie_secure,
    cookie_httponly,
    secret,
    ):
    cookieval = signed_serialize(request.session.session_id, secret)
    response.set_cookie(
        cookie_name,
        value=cookieval,
        max_age=cookie_max_age,
        path=cookie_path,
        domain=cookie_domain,
        secure=cookie_secure,
        httponly=cookie_httponly,
        )
Example #16
0
            def set_cookie_callback(request, response):
                """
                The set cookie callback will first check to see if we're in an
                exception. If we're in an exception and ``cookie_on_exception``
                is False, we return immediately before setting the cookie.

                For all other cases the cookie will be set normally.
                """
                exc = getattr(request, 'exception', None)
                # exit early if there's an exception and the user specified
                # to not set cookies on exception
                if exc is not None and not cookie_on_exception:
                    return
                cookieval = signed_serialize(session_key, secret)
                response.set_cookie(
                    cookie_name,
                    value=cookieval,
                    max_age=cookie_max_age,
                    domain=cookie_domain,
                    secure=cookie_secure,
                    httponly=cookie_httponly,
                    )
Example #17
0
 def _serialize(self, accessed, state, secret='secret'):
     from pyramid.session import signed_serialize
     return signed_serialize((accessed, accessed, state), secret)
Example #18
0
 def _callFUT(self, data, secret):
     from pyramid.session import signed_serialize
     return signed_serialize(data, secret)
Example #19
0
 def _serialize(self, value):
     from pyramid.compat import bytes_
     from pyramid.session import signed_serialize
     return bytes_(signed_serialize(value, 'secret'))
Example #20
0
 def _serialize(self, accessed, state, secret='secret'):
     from pyramid.session import signed_serialize
     return signed_serialize((accessed, accessed, state), secret)
 def _callFUT(self, data, secret):
     from pyramid.session import signed_serialize
     return signed_serialize(data, secret)
 def _serialize(self, value):
     from pyramid.compat import bytes_
     from pyramid.session import signed_serialize
     return bytes_(signed_serialize(value, 'secret'))
Example #23
0
 def _serialize(self, value):
     from pyramid.session import signed_serialize
     return signed_serialize(value, 'secret')
Example #24
0
 def _serialize(self, session_id, secret='secret'):
     from pyramid.session import signed_serialize
     return signed_serialize(session_id, secret)
Example #25
0
 def signed_session_id(self):
     session_id = self.session_id
     return signed_serialize(session_id,
                             secret) if session_id is not None else None
Example #26
0
def login(request):
    page_title = 'Login'

    user = get_user(request)

    if request.referer:
        referer_host = request.referer.split('/')[2]
    else:
        referer_host = None

    if request.referer and referer_host == request.host and request.referer.split(
            '/')[3][:6] != 'logout':
        return_url = request.referer
    elif request.path != '/login':
        return_url = request.url
    else:
        return_url = '/applications'

    login = ''
    password = ''
    error = ''

    if 'form.submitted' in request.POST:
        login = request.POST['login']
        password = request.POST['password']

        # AD/LDAP
        if request.registry.settings['tcw.auth_mode'] == 'ldap':
            connector = get_ldap_connector(request)
            data = connector.authenticate(login, password)
        # LOCAL
        else:
            data = local_authenticate(login, password)

        if data is not None:
            dn = data[0]
            encrypted = signed_serialize(
                login, request.registry.settings['tcw.cookie_token'])
            headers = remember(request, dn)
            headers.append(
                ('Set-Cookie',
                 'un=' + str(encrypted) + '; Max-Age=604800; Path=/'))

            return HTTPFound(request.POST['return_url'], headers=headers)
        else:
            error = 'Invalid credentials'

    if request.authenticated_userid:

        if request.path == '/login':
            error = 'You are already logged in'
            page_title = 'Already Logged In'
        else:
            error = 'You do not have permission to access this page'
            page_title = 'Access Denied'

    return {
        'layout': site_layout(),
        'page_title': page_title,
        'user': user,
        'return_url': return_url,
        'login': login,
        'password': password,
        'error': error,
    }
Example #27
0
def userCookieString(userName):
    return signed_serialize({'userName':userName, 'passwordHash': getSavedPasswordHash(userName)},
                                   COOKIE_SECRET_KEY)
Example #28
0
def login(request):
    page_title = 'Login'

    au = get_authenticated_user(request)

    if request.referer:
        referer_host = request.referer.split('/')[2]
    else:
        referer_host = None

    # Need to send the client a 401 so it can send a user/pass to auth. Need a second condition to check for authenticated user
    if request.path_info.split('/')[1][:3] == 'api':
        logging.debug('request came from the api, sending request to re-auth')
        return HTTPUnauthorized()

    if request.referer and referer_host == request.host and request.referer.split('/')[3][:6] != 'logout':
        return_url = request.referer
    elif request.path != '/login':
        return_url = request.url
    else:
        return_url = '/'

    login = ''
    password = ''
    error = ''

    if 'form.submitted' in request.POST:
        login = request.POST['login']
        password = request.POST['password']

        # Try local first, ldap second
        data = local_authenticate(login, password)
        if data is None:
            connector = get_ldap_connector(request)
            data = connector.authenticate(login, password)
            
        if data is not None:
            dn = data[0]
            encrypted = signed_serialize(login, request.registry.settings['arsenal.cookie_token'])
            headers = remember(request, dn)
            headers.append(('Set-Cookie', 'un=' + str(encrypted) + '; Max-Age=604800; Path=/'))

            if 'api.client' in request.POST:
                return HTTPOk(headers=headers)
            else:
                return HTTPFound(request.POST['return_url'], headers=headers)
        else:
            error = 'Invalid credentials'
            if 'api.client' in request.POST:
                return HTTPForbidden()

    if request.authenticated_userid:

        if request.path == '/login':
            error = 'You are already logged in'
            page_title = 'Already Logged In'
        else:
            error = 'You do not have permission to access this page'
            page_title = 'Access Denied'
            if 'api.client' in request.POST:
                return HTTPForbidden()

    return {'layout': site_layout('max'),
            'page_title': page_title,
            'au': au,
            'return_url': return_url,
            'login': login,
            'password': password,
            'error': error,
           }
Example #29
0
 def _serialize(self, value):
     from pyramid.session import signed_serialize
     return signed_serialize(value, 'secret')
 def _serialize(self, session_id, secret='secret'):
     from pyramid.session import signed_serialize
     return signed_serialize(session_id, secret)
def set_secure_cookie(response, key, value, **kw):
    """Sets a secure/signed cookie."""
    signed_value = signed_serialize(value, SETTINGS['cookie.secret'])

    response.set_cookie(key, signed_value, **kw)