Beispiel #1
0
 def set_unread_message_total(self, total):
     decoded_token = self.get_decoded_jwt()
     decoded_token['unread_message_count']['value'] = total
     decoded_token['unread_message_count'][
         'refresh_in'] = _get_new_timestamp(ttl=300)
     self.encoded_jwt_token = jwt.encode(decoded_token)
     self.save()
Beispiel #2
0
 def from_party_id(cls, party_id):
     """Create a new and unpersisted session object from a party_id, this will encode a JWT
         and set an expiry time, it will default the unread message count to 0"""
     data_dict = {
         'party_id': party_id,
         "role": "respondent",
         'unread_message_count': {
             'value': 0,
             'refresh_in': _get_new_timestamp(ttl=300)
         },
         'expires_in': _get_new_timestamp()
     }
     encoded_jwt_token = jwt.encode(data_dict)
     session_key = str(uuid4())
     session = cls(session_key, encoded_jwt_token)
     return session
Beispiel #3
0
    def test_get_message_count_from_api_when_expired(self, headers):
        headers.return_value = {'Authorization': "token"}
        session = Session.from_party_id("id")
        decoded = session.get_decoded_jwt()
        decoded['unread_message_count']['refresh_in'] = (
            datetime.fromtimestamp(
                decoded['unread_message_count']['refresh_in']) -
            timedelta(seconds=301)).timestamp()
        encoded = jwt.encode(decoded)
        session.encoded_jwt_token = encoded
        with responses.RequestsMock() as rsps:
            rsps.add(rsps.GET,
                     url_get_conversation_count,
                     json=message_count,
                     status=200,
                     headers={'Authorisation': 'token'},
                     content_type='application/json')
            with app.app_context():
                count = conversation_controller.try_message_count_from_session(
                    session)

                self.assertEqual(3, count)
 def test_encode_jwt(self):
     my_encoded_dictionary = encode(data_dict_for_jwt_token)
     my_decoded_dictionary = decode(my_encoded_dictionary)
     self.assertEqual(my_decoded_dictionary, data_dict_for_jwt_token)
Beispiel #5
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)
Beispiel #6
0
 def refresh_session(self):
     """ Refesh a session by setting a new expiry timestamp """
     decoded_jwt = self.get_decoded_jwt()
     decoded_jwt["expires_in"] = _get_new_timestamp()
     self.encoded_jwt_token = jwt.encode(decoded_jwt)
     self.save()