Exemplo n.º 1
0
    def test_get_encoded_jwt(self):
        # Create session and get session key
        session = SessionHandler()
        session.create_session(encoded_jwt='test_jwt')
        session_key = session.session_key

        encoded_jwt = session.get_encoded_jwt(session_key)

        self.assertEqual(encoded_jwt, 'test_jwt'.encode())
Exemplo n.º 2
0
    def test_create_session(self):
        # Create session and get session key
        session = SessionHandler()
        session.create_session(encoded_jwt='test_jwt')
        session_key = session.session_key

        # Retrieve encoded_jwt from session
        test_jwt = self.redis.get(session_key)
        self.assertEqual(test_jwt, 'test_jwt'.encode())
class TestJWTAuthorization(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        self.app.testing = True
        self.session = SessionHandler()

    def tearDown(self):
        self.session.delete_session(self.session.session_key)

    @staticmethod
    def decorator_test(request):
        @jwt_authorization(request)
        def test_function(session):
            pass

        test_function()

    def test_jwt_authorization_success(self):
        self.session.create_session(valid_jwt)
        request = mock.MagicMock(
            cookies={"authorization": self.session.session_key})

        # If this function runs without exceptions the test is considered passed
        self.decorator_test(request)

    def test_jwt_authorization_no_jwt(self):
        request = mock.MagicMock()

        with self.assertRaises(JWTValidationError):
            self.decorator_test(request)

    def test_jwt_authorization_expired_jwt(self):
        self.session.create_session(expired_jwt)
        request = mock.MagicMock(
            cookies={"authorization": self.session.session_key})

        with self.assertRaises(JWTValidationError):
            self.decorator_test(request)

    def test_jwt_authorization_no_exipry(self):
        self.session.create_session(no_expiry_jwt)
        request = mock.MagicMock(
            cookies={"authorization": self.session.session_key})

        with self.assertRaises(JWTValidationError):
            self.decorator_test(request)

    @mock.patch('frontstage.common.authorisation.decode')
    def test_jwt_authorization_decode_failure(self, mock_decode):
        self.session.create_session(valid_jwt)
        request = mock.MagicMock(
            cookies={"authorization": self.session.session_key})
        mock_decode.side_effect = JWTError

        with self.assertRaises(JWTValidationError):
            self.decorator_test(request)
Exemplo n.º 4
0
def logout():
    # Delete user session in redis
    session_key = request.cookies.get('authorization')
    session = SessionHandler()
    session.delete_session(session_key)

    # Delete session cookie
    response = make_response(redirect(url_for('sign_in_bp.login')))
    response.set_cookie('authorization', value='', expires=0)
    return response
def _create_get_conversation_headers():
    try:
        encoded_jwt = SessionHandler().get_encoded_jwt(
            request.cookies['authorization'])
    except KeyError:
        logger.error('Authorization token missing in cookie')
        raise AuthorizationTokenMissing
    return {'Authorization': encoded_jwt}
def _create_send_message_headers():
    try:
        encoded_jwt = SessionHandler().get_encoded_jwt(
            request.cookies['authorization'])
    except KeyError:
        logger.error('Authorization token missing in cookie')
        raise AuthorizationTokenMissing
    return {
        'Authorization': encoded_jwt,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
Exemplo n.º 7
0
    def test_delete_session(self):
        # Create session and get session key
        session = SessionHandler()
        session.create_session(encoded_jwt='test_jwt')
        session_key = session.session_key
        session.delete_session(session_key)

        session = redis.get(session_key)

        self.assertEqual(session, None)
Exemplo n.º 8
0
    def test_update_session_with_session_key(self):
        # Create session and get session key
        session = SessionHandler()
        session.create_session(encoded_jwt='test_jwt')
        session_key = session.session_key

        # Wait 3 seconds and update the session
        time.sleep(3)
        session.update_session(session_key)

        # Check that the session expiry time has been reset
        expires_in = redis.ttl(session_key)
        self.assertEqual(expires_in, 3600)
Exemplo n.º 9
0
def login():
    form = LoginForm(request.form)
    form.username.data = form.username.data.strip()
    account_activated = request.args.get('account_activated', None)

    if request.method == 'POST' and form.validate():
        username = form.username.data
        password = request.form.get('password')

        party_json = party_controller.get_respondent_by_email(username)
        if not party_json or 'id' not in party_json:
            logger.info(
                'Respondent not able to sign in as they don\'t have an active account in the system.'
            )
            return render_template('sign-in/sign-in.html',
                                   form=form,
                                   data={"error": {
                                       "type": "failed"
                                   }})
        party_id = party_json['id']

        try:
            oauth2_token = oauth_controller.sign_in(username, password)
        except OAuth2Error as exc:
            error_message = exc.oauth2_error
            if USER_ACCOUNT_LOCKED in error_message:
                logger.info('User account is locked on the OAuth2 server',
                            party_id=party_id)
                if party_json['status'] == 'ACTIVE' or party_json[
                        'status'] == 'CREATED':
                    notify_party_and_respondent_account_locked(
                        respondent_id=party_id,
                        email_address=username,
                        status='SUSPENDED')
                return render_template('sign-in/sign-in.account-locked.html',
                                       form=form)
            elif BAD_AUTH_ERROR in error_message:
                return render_template('sign-in/sign-in.html',
                                       form=form,
                                       data={"error": {
                                           "type": "failed"
                                       }})
            elif NOT_VERIFIED_ERROR in error_message:
                logger.info(
                    'User account is not verified on the OAuth2 server')
                return render_template(
                    'sign-in/sign-in.account-not-verified.html',
                    party_id=party_id,
                    email=username)
            else:
                logger.info(
                    'OAuth 2 server generated 401 which is not understood',
                    oauth2_error=error_message)
                return render_template('sign-in/sign-in.html',
                                       form=form,
                                       data={"error": {
                                           "type": "failed"
                                       }})

        # Take our raw token and add a UTC timestamp to the expires_at attribute
        data_dict = {**oauth2_token, 'party_id': party_id}
        data_dict_for_jwt_token = timestamp_token(data_dict)
        encoded_jwt_token = encode(data_dict_for_jwt_token)
        response = make_response(
            redirect(
                url_for('surveys_bp.get_survey_list',
                        tag='todo',
                        _external=True,
                        _scheme=getenv('SCHEME', 'http'))))

        session = SessionHandler()
        logger.info('Creating session', party_id=party_id)
        session.create_session(encoded_jwt_token)
        response.set_cookie('authorization',
                            value=session.session_key,
                            expires=data_dict_for_jwt_token['expires_at'])
        logger.info('Successfully created session',
                    party_id=party_id,
                    session_key=session.session_key)
        return response

    template_data = {
        "error": {
            "type": form.errors,
            "logged_in": "False"
        },
        'account_activated': account_activated
    }
    return render_template('sign-in/sign-in.html',
                           form=form,
                           data=template_data)
 def setUp(self):
     self.app = app.test_client()
     self.app.testing = True
     self.session = SessionHandler()